/*
 * Device.hpp
 *
 * Created on: $(date:yyyy-MM-dd)
 * Author: $(user)
 */

#ifndef Device_H
#define Device_H

#include "common.h"

using namespace std;

template <class T>
class Device{
public:
    int m_fd;
    string deviceName;
    string deviceType;
    string m_buf;

    virtual void func(T &data) = 0;

    string getDeviceName();
    string getDeviceType();

    bool getBuf(const int time = 500000);

    Device();
    Device(const string& devicePath, const string& dt, const int speed = 9600);
    ~Device();
};

template <class T>
Device<T>::Device(){
}

template <class T>
Device<T>::Device(const string& devicePath, const string& dt, const int speed){
    deviceName = devicePath;
    deviceType = dt;
    
    // 打开串口设备
    m_fd = open(deviceName.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);

    // 设置串口参数
    set_uart(m_fd, speed, 8, 'N', 1);
}

template <class T>
Device<T>::~Device(){
    close(m_fd);
}


template <class T>
string Device<T>::getDeviceName() {
    return deviceName;
}

template <class T>
string Device<T>::getDeviceType(){
    return deviceType;
}

template <class T>
bool Device<T>::getBuf(const int time) {
    char buf[1024];
    int count = 0;
    
    // 检查高度计串口是否打开成功
    if (m_fd < 0) {
        cout << "open " << deviceName << " error " << endl;
        close(m_fd);
        
        return false;
    }
    
    // 清空输入缓冲区，丢弃之前的所有数据
    // tcflush(m_fd, TCIFLUSH);
    
    // memset(buf, 0, sizeof(buf));
    // usleep(time);
    
    // count = read(m_fd, buf, sizeof(buf)-1);
    // buf[count] = '\0';
    
    // m_buf = buf;
    
    
    bool hasData = false;
    // 等待并读取最新的一条完整数据
    do {
        memset(buf, 0, sizeof(buf));
        count = read(m_fd, buf, sizeof(buf) - 1);  // 留1字节给终止符
        if (count > 0) {
            buf[count] = '\0';  // 字符串终止
            m_buf = buf;
            hasData = true;
        } else {
            usleep(time);  // 短暂延时后重试
        }
    } while (!hasData);

    return true;
}

#endif // Device_H
